package top.infopub.mgr.mkt.service.impl;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.dto.mkt.DiscloseProDto;
import top.infopub.enums.mkt.*;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.bpa.domain.BpaProjectDomain;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.cnst.FlowTemplateEnum;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.mgr.flow.service.WsFlowProcessService;
import top.infopub.mgr.mkt.dao.*;
import top.infopub.mgr.mkt.domain.DiscloseProDomain;
import top.infopub.mgr.mkt.jsonvo.DiscloseProJsonVo;
import top.infopub.mgr.mkt.service.DiscloseProService;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.mgr.mkt.service.SetupProService;
import top.infopub.mgr.mkt.vo.DiscloseProVo;
import top.infopub.model.mkt.*;
import top.infopub.security.vo.AuthorizationVO;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Service
public class DiscloseProServiceImpl extends GenericServiceImpl<DisclosePro, String> implements DiscloseProService {

    @Autowired
    private DiscloseProDao discloseProDao;

    @Autowired
    private DiscloseProCoopDao discloseProCoopDao;

    @Autowired
    private DiscloseProSubDao discloseProSubDao;

    @Autowired
    private DiscloseProQuoteDao discloseProQuoteDao;

    @Autowired
    private DiscloseProAttDao discloseProAttDao;

    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;

    @Autowired
    private ProjectInfoDao projectInfoDao;

    @Autowired
    private WsFlowProcessService wsFlowProcess;

    @Autowired
    private SetupProService setupProService;

    @Autowired
    private ProProcessManageService proProcessManageService;

    @Autowired
    private OAFlowService oaFlowService;

    @Override
    public GenericDao<DisclosePro, String> getDao() {
        return discloseProDao;
    }

    @Override
    public Page<DiscloseProDomain> selectPageByDomainWhere(Page<DiscloseProDomain> page,
                                                           DiscloseProVo discloseProVo) throws ParseException {
        //处理时间范围
        if (!StringUtils.isEmpty(discloseProVo.getDates()))
        {
            String[] splitTime = discloseProVo.getDates().split("~");
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            discloseProVo.setStartDate(format.parse(splitTime[0]));
            discloseProVo.setEndDate(format.parse(splitTime[1]));
        }
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<DiscloseProDomain>)discloseProDao.selectByDomainWhere(discloseProVo);
    }

    @Override
    public Page<DiscloseProDomain> selectMyCheckByDomainWhere(Page<DiscloseProDomain> page,
                                                              DiscloseProVo discloseProVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<DiscloseProDomain>)discloseProDao.selectMyCheckByDomainWhere(discloseProVo);
    }

    @Override
    public DiscloseProVo selectById(String id) {
        return discloseProDao.selectById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addDisclosePro(DisclosePro disclosePro, List<DiscloseProCoop> discloseProCoops,
                               List<DiscloseProSub> discloseProSubs,
                               List<DiscloseProQuote> discloseProQuotes,
                               List<DiscloseProAtt> discloseProAtts) {
        //插入预立项记录
        discloseProDao.insertById(disclosePro);

        //批量插入联合体单位
        if (CollectionUtils.isNotEmpty(discloseProCoops)) {
            discloseProCoopDao.insertByBatch(discloseProCoops);
        }

        //批量插入子项
        if (CollectionUtils.isNotEmpty(discloseProSubs)) {
            discloseProSubDao.insertByBatch(discloseProSubs);
        }

        //批量插入投标报价
        if (CollectionUtils.isNotEmpty(discloseProQuotes)) {
            discloseProQuoteDao.insertByBatch(discloseProQuotes);
        }

        //批量插入附件
        if (CollectionUtils.isNotEmpty(discloseProAtts)) {
            discloseProAttDao.insertByBatch(discloseProAtts);
        }

        // 注意 这里根据不同的业务分支判断条件 获得不同enum
        FlowTemplateEnum templateEnum = FlowTemplateEnum.MKT_DISCLOSE_PRO;
        // 处理工作流数据
        wsFlowProcess.launch(templateEnum, disclosePro.getId(), disclosePro.getProcessId(), null);

    }

    @Override
    public List<DisclosePro> selectUsableDisclosePro() {
        return discloseProDao.selectUsableDisclosePro();
    }

    @Override
    public List<DisclosePro> selectAllUsableDisclosePro(String ids, String proCodes) {
        return discloseProDao.selectAllUsableDisclosePro(ids, proCodes,
            wsFlowProcess.proxyVisibleProCodes());
    }

    @Override
    public List<DisclosePro> selectAllDisclosePro() {
        return discloseProDao.selectAllDisclosePro(wsFlowProcess.proxyVisibleProCodes());
    }

    @Override
    public List<DisclosePro> selectAllWithOrg() {
        return discloseProDao.selectAllWithOrg();
    }

    @Override
    public List<DisclosePro> selectByProCode(String proCode) {
        return discloseProDao.selectByProCode(proCode);
    }

    @Override
    public DiscloseProJsonVo queryDetailById(String id) {
        DiscloseProJsonVo disProJson = new DiscloseProJsonVo();
        //基础信息
        DiscloseProDto disProDto = discloseProDao.queryDetailById(id);
        InBoundTypeEnum pfe = InBoundTypeEnum.getByCode(disProDto.getIsInStore());
        if (pfe != null) {
            disProDto.setIsInStore(pfe.getName());
        }
        disProJson.setInfo(disProDto);

        //附件信息表
        List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(disProDto.getProCode(), ProjectFileTypeEnum.FILE_TYPE30.getCode(), null);
        disProJson.setFileAtt(setupProService.fileAttaListToArray(projectAttaList));
        return disProJson;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RspVo editDetail(DisclosePro disPro, List<ProjectAttachment> attachmentList, AuthorizationVO vo, Integer submitType) {
        //根据pro_code查询项目基础信息
        ProjectInfo tmpProInfo = projectInfoDao.findByProCode(disPro.getProCode());
        if (tmpProInfo == null) return RspVo.getFailureResponse(400, "项目基础信息不存在");
        DisclosePro tmpDp = discloseProDao.selectByPrimaryKey(disPro.getId());
        if (tmpDp == null) return RspVo.getFailureResponse(400, "交底信息不存在");
        //判断审批状态
        if (StringUtils.isNotBlank(tmpDp.getProcessStatus())
                && (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), tmpDp.getProcessStatus())
                || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), tmpDp.getProcessStatus()))) {
            return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
        }

        //更新投标决策信息
        disPro.setUptBy(vo.getId());
        disPro.setUptTime(new Date());
        discloseProDao.updateByIdSelective(disPro);

        //更新附件信息
        projectAttachmentDao.deleteByWhere(disPro.getProCode(), ProjectFileTypeEnum.FILE_TYPE30.getCode(), null);
        if (attachmentList != null && attachmentList.size() > 0) {
            projectAttachmentDao.insertBatch(attachmentList);
        }

        if (submitType == 1) {
            //处理OA待办信息
            if (StringUtils.isNotBlank(tmpDp.getOaId())) {
                oaFlowService.finishOA(tmpDp.getOaId());
            }
            String detailJson = JSON.toJSONString(queryDetailById(disPro.getId()));
            proProcessManageService.sendProcess(ProProcessDetailTypeEnum.PRO_NODE_TYPE12, detailJson, disPro.getId(), disPro.getProCode(), vo);
        }
        return RspVo.getSuccessResponse();
    }

    @Override
    public List<BpaProjectDomain> selectProject() {
        return discloseProDao.selectProject();
    }
}
